package com.testing.vip14login.controller;

import com.testing.vip14login.mapper.PersonMapper;
import com.testing.vip14login.model.Person;
import com.testing.vip14login.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname PersonController
 * @Description 类型说明
 * @Date 2023/9/28 20:11
 * @Created by 特斯汀Roy
 */
@RestController
@RequestMapping("/person")
public class PersonController {
    @Autowired
    PersonMapper personMapper;

    //存储
    public List<Person> personList = new ArrayList<>();

    //查
    @GetMapping
    public Result<List<Person>> getAllPerson() {
//        return new Result<List<Person>>(200, "查询成功", personList);
        return Result.success("查询成功",personMapper.listPersons());
    }

    //增
    @PostMapping
    public Result addNewPerson(@RequestParam String username, @RequestParam Integer age, @RequestParam Integer salary) {
//        Person person = new Person(username, age, salary);
//        personList.add(person);
//        return Result.success("新增数据",person);
        int i = personMapper.addPerson(username, age, salary);
        if (i > 0) {
            return Result.success("新增成功", username);
        }
        return new Result(201, "新增失败", username);
    }

    //改
    @PutMapping
    public Result changeSalary(@RequestBody Person person) {
//        for (Person personInList : personList) {
//            if (personInList.getUsername().equals(person.getUsername())) {
//                personInList.setSalary(person.getSalary());
//            }
//        }
        int i = personMapper.updatePerson(person);
        if(i>0) {
            return Result.success("修改数据成功", person);
        }
        return new Result(204,"修改失败",person);
    }

    //删
    @DeleteMapping("/{username}")
    public Result leave(@PathVariable String username) {
        //记录一下当前的下标
//        int target = -1;
//        for (Person person : personList) {
//            if (person.getUsername().equals(username)) {
//                //找到了username所代表的元素，记录它的下标
//                target = personList.indexOf(person);
//            }
//        }
//        //判断是否找到了想要删除的用户
//        if (target != -1) {
//            personList.remove(target);
//            return Result.success("删除成功", target);
//        }
        personMapper.deleteByUserName(username);
        return new Result(-1, "删除失败", "没有用户名为" + username + "的用户");

    }
}
